package top.ljlgithub.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import top.ljlgithub.domain.PageBean;
import top.ljlgithub.domain.PageConditionSql;
import top.ljlgithub.domain.QueryCondition;
import top.ljlgithub.domain.User;
import top.ljlgithub.service.AdminService;
import top.ljlgithub.service.UserService;
import top.ljlgithub.vo.LoginParam;
import top.ljlgithub.vo.PageParam;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * @ClassName
 * @Description TODO
 * @Author L1470
 * @Date 2021/3/21 8:39
 * @Version 1.0
 **/
@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private UserService userService;
    @RequestMapping("/deleteUsers")
    public String deleteUsers(HttpServletRequest request,int[] uid){
        if (request.getSession().getAttribute("role") == null){
            return "forward:/index.jsp";
        }
        adminService.removeUsers(uid);
        return "redirect:/admin/findAll.do";
    }
    @RequestMapping("/deleteUser")
    public String deleteUser(int id,HttpServletRequest request){
        if (request.getSession().getAttribute("role") == null){
            return "forward:/index.jsp";
        }
        adminService.removeUser(id);
        return "redirect:/admin/findAll.do";
    }
    @RequestMapping("/updateUser")
    public String updateUser(User user){
        adminService.updateUser(user);
        return "redirect:/admin/findAll.do";
    }
    @RequestMapping("/toUpdateUser")
    public String toUpdateUser(int id,HttpServletRequest request){
        if (request.getSession().getAttribute("role") == null){
            return "forward:/index.jsp";
        }
        User user = adminService.findUserById(id);
        request.setAttribute("user",user);
        return "updateUser";
    }
    @RequestMapping("/toAddUser")
    public String toAddUser(HttpServletRequest request){
        if (request.getSession().getAttribute("role") == null){
            return "forward:/index.jsp";
        }
        return "addUser";
    }
    @RequestMapping("/addUser")
    public String addUser(User user){
        adminService.addUser(user);
        return "redirect:/admin/findAll.do";
    }
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("role");
        return "redirect:/user/findAll.do";
    }
    @RequestMapping("/adminJudge")
    public String adminJudge(HttpServletRequest request){
        Object role = request.getSession().getAttribute("role");
        if (role != null){
            return "forward:/admin/findAll.do";
        }
        return "forward:/login.jsp";
    }
    @RequestMapping("/login")
    public String login(HttpServletRequest request, LoginParam loginParam) {
        //1.获取session中验证码与用户请求的验证码比较
        String code = loginParam.getCode();
        //String checkCode = (String) request.getSession().getAttribute("checkCode_session");
        //做到验证码每次都更新，只能用一次
        //用户可能使用缓存来进行提交数据，而服务器没有存储验证码
        //而强转null会导致空指针异常，所以应该转发到登录界面
        //因为要告诉用户验证码已失效，重新输入
        String checkCode ="";
        if (request.getSession().getAttribute("checkCode_session") != null){
            request.getSession().removeAttribute("error");

            checkCode = (String) request.getSession().getAttribute("checkCode_session");
        }else {
            request.getSession().setAttribute("error","验证码已过期,请重新输入");
            return "redirect:/login.jsp";
        }
        request.getSession().removeAttribute("checkCode_session");
        if (checkCode.equalsIgnoreCase(code)) {
            //1.验证码正确
            //1.1判断用户名和密码是否正确
            int result = adminService.checkAdmin(loginParam);
            //mysql查询数据自动忽略大小写
            if (result == 1) {
                //用户名和密码都正确
                //2.重定向到success.jsp页面
                //注意重定向是新的用户请求，不能直接跳转到WEB-INF目录下的资源
                //return "redirect:/WEB-INF/jsp/allUser.jsp";
                request.getSession().setAttribute("role", "管理员");
                return "forward:/admin/findAll.do";
            } else {
                //用户名或密码错误
                //1.存储提示信息
                request.setAttribute("error", "用户名或密码错误");
                //2.转发
                return "forward:/login.jsp";
            }

        } else {
            //2.验证码错误
            //2.1将提示信息存储到request
            request.setAttribute("error", "验证码错误");
            //2.2转发到登录页面
            return "forward:/login.jsp";
        }
    }
    @RequestMapping("/findAll")
    public ModelAndView findAll(PageConditionSql pageConditionSql, QueryCondition queryCondition, HttpServletRequest request) {
        //判断用户是否是管理员
        ModelAndView mv = new ModelAndView();
        Object role = request.getSession().getAttribute("role");
        if (role == null){
            mv.setViewName("redirect:/index.jsp");
            return mv;
        }
        if (pageConditionSql.getCurrentPage() == 0){
            pageConditionSql.setCurrentPage(1);
        }
        if (pageConditionSql.getRows() == 0){
            pageConditionSql.setRows(5);
        }
        pageConditionSql.setCondition(queryCondition);
        request.setAttribute("condition",queryCondition);
        PageBean<User> page = adminService.getUserByPage(pageConditionSql);
        mv.addObject("currentPage",pageConditionSql.getCurrentPage());
        mv.addObject("page",page);
        request.setAttribute("role", "管理员");
        mv.setViewName("allUser");
        return mv;
    }

    @RequestMapping("/checkCode")
    public void checkCode(HttpServletResponse response, HttpServletRequest request) throws IOException {
        //设置图片的尺寸
        int width = 100;
        int height = 50;
        //1.在内存中获取图片对象,bufferedImage
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //2.美化图片
        //2.0获取画笔对象
        Graphics g = image.getGraphics();
        g.setColor(Color.lightGray);
        //2.1填充颜色
        g.fillRect(0, 0, width, height);
        //2.2画矩形边框,由于边框有1px的厚度
        g.setColor(Color.BLUE);
        g.drawRect(0, 0, width - 1, height - 1);
        //2.3写入验证码
        int codeCount = 4;//验证码的个数
        int codeHeight = height / 2;//验证码的起始高度
        int codeWidth = 0;//验证码的起始宽度

        //获取验证码的字符集
        char[] chars = new char[62];//用于存储字母和数字
        char start = 'a';
        for (int i = 0; i < 26; i++) {
            chars[i] = (char) (start + i);
        }
        start = 'A';
        for (int i = 26; i < 52; i++) {
            chars[i] = (char) (start + i - 26);
        }
        start = '0';
        for (int i = 52; i < 62; i++) {
            chars[i] = (char) (start + i - 52);
        }
        Random r = new Random();
        //设置验证码的字体大小和格式
        g.setFont(new Font("宋体", Font.ITALIC, 30));
        Color[] colors = {Color.blue,Color.red,Color.yellow};
        //拼接验证码字符串，返回
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= codeCount; i++) {
            int index = r.nextInt(chars.length);
            int color = r.nextInt(colors.length);
            g.setColor(colors[color]);
            String s = "" + chars[index];
            sb.append(s);
            if (i == 1) {
                g.drawString(s, 10 + r.nextInt(5) - 2, codeHeight + 5);
            } else {
                g.drawString(s, ((width / (codeCount + 1)) * i) + r.nextInt(5) - 2, codeHeight + 5);
            }
        }
        //将StringBuilder转换为String存储到session，因为是两次请求，要共享数据，只能使用session
        request.getSession().setAttribute("checkCode_session", sb.toString());
        //4.添加干扰线
        int lineCount = 10;
        g.setColor(Color.GRAY);
        for (int i = 0; i < 10; i++) {
            int x1 = r.nextInt(width);
            int x2 = r.nextInt(width);
            int y1 = r.nextInt(height);
            int y2 = r.nextInt(height);
            g.drawLine(x1, y1, x2, y2);
        }
        //3.将图片进行输出
        ImageIO.write(image, "jpg", response.getOutputStream());
    }



}
//服务器端的输出
//1.totalCount,总记录数
//2.pageCount,总页数=总记录数 % 每页的记录数 == 0 ? 总记录数 / 每页的记录数 : 总记录数 / 每页的记录数+1
//3.rows，每页的记录数
//4.list：用于展示数据
//5.使用limit语句
//select * from user limit  (current-1)*rows  rows,
//客户端的输入
//1.每页的记录数
//2.当前页吗

//分页条件查询
//输出，totalCount，totalPage，users，输出是不变的，jsp可以不用改
//输入：条件，name，address，email，currentPage，rows


